<template>
	<div>
		<el-dialog title="设置岗位" :close-on-click-modal="false" v-model="visible" width="50%" @close="refreshEmit" >
			<el-tree :data="treeStationList" v-loading.fullscreen.lock="loading" ref="stationtree" node-key="id" :props="defaultProps1" :default-expand-all="true" show-checkbox check-strictly  :highlight-current="true">
			</el-tree>
			<template #footer>
				<span>
					<el-button @click="visible = false">取消</el-button>
					<el-button type="primary" @click="save()">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, defineComponent, nextTick } from 'vue';
import {systemApi} from '/@/api/systemapi'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import type { ElTree } from 'element-plus'
export default defineComponent ({
	setup(props, ctx) {
		const stationtree = ref<InstanceType<typeof ElTree>>()
		const state = reactive({
			loading: false,
			visible: false,
			treeStationList: [],
			userId: '',
			defaultProps1: {
				children: 'childList',
				label: 'name'
			}
		})
		// 打开弹窗
		const openDialog = (id: string, tenantId: string) => {
			state.userId = id
			getTreeStationList(id, tenantId)
			state.visible = true
		}
		const getTreeStationList = (id: string, tenantId: string) => {
			state.loading = true
			systemApi().getTreeStationList(tenantId).then(data => {
				if (data) {
					state.treeStationList = data
					systemApi().getUserStationList(id).then(datas => {
					// console.log(datas)
					if (datas && datas.code === 0) {
						nextTick(()=>{
							datas.stationList.forEach((item, index, arr) => {
								// console.log(this.$refs.stationtree)
								stationtree.value!.setChecked(item.stationId, true, false)
							})
						})
					}
					}).catch(() => {
					})
				} else {
					state.treeStationList = []
				}
			}).finally(() => {
				state.loading = false
			})
		}
		const refreshEmit = () => {
			closeDialog()
			ctx.emit('refreshDataList')
		}
		// 关闭弹窗
		const closeDialog = () => {
			state.visible = false;
		}
		const save = () => {
			const loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			systemApi().setUserStation(state.userId, stationtree.value!.getCheckedNodes()).then(data => {
				if (data && data.code === 0) {
					ElMessage.success('设置成功')
					ctx.emit('refreshDataList')
					state.visible = false
				} else {
					ElMessage.error(data.msg)
				}
			}).catch(() => {
				ElMessage.error('设置失败')
			}).finally(() => {
				loading.close()
			})
		}
		return{
			closeDialog,
			refreshEmit,
			openDialog,
			stationtree,
			getTreeStationList,
			save,
			...toRefs(state),
		}
	}
})
</script>